<template>
  <div class="app-container">
    <!-- 搜索工作栏 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="110px">
      <el-form-item label="订单号" prop="channelOrderNo">
        <el-input v-model="queryParams.channelOrderNo" placeholder="请输入订单号" clearable
                  @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商户单订单号" prop="merchantOrderNo">
        <el-input v-model="queryParams.merchantOrderNo" placeholder="请输入商户单订单号" clearable
                  @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="渠道用户名称" prop="channelUserName">
        <el-input v-model="queryParams.channelUserName" placeholder="请输入渠道用户名称" clearable
                  @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="联系方式" prop="channelUserPhone">
        <el-input v-model="queryParams.channelUserPhone" placeholder="请输入联系方式" clearable
                  @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="支付状态" prop="payStatus">
        <el-select v-model="queryParams.payStatus" placeholder="请选择支付状态" filterable clearable size="small">
          <el-option v-for="dict in this.getDictDatas(DICT_TYPE.app_pay_status)"
                     :key="dict.value" :label="dict.label" :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="订单状态" prop="channelStatus">
        <el-select v-model="queryParams.channelStatus" placeholder="请选择订单状态"
                   filterable clearable size="small"
        >
          <el-option v-for="dict in this.getDictDatas(DICT_TYPE.pc_app_channel_status)"
                     :key="dict.value" :label="dict.label" :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="商户订单状态" prop="reportStatus">
        <el-select v-model="queryParams.merchantStatus" placeholder="请选择订单状态"
                   filterable clearable size="small"
        >
          <el-option v-for="dict in this.getDictDatas(DICT_TYPE.app_merchant_status)"
                     :key="dict.value" :label="dict.label" :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="订单时间" prop="channelOrderTime">
        <el-date-picker v-model="queryParams.channelOrderTime" style="width: 240px" value-format="yyyy-MM-dd HH:mm:ss"
                        type="daterange"
                        range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"
                        :default-time="['00:00:00', '23:59:59']"
        />
      </el-form-item>
      <el-form-item label="完成时间" prop="completionTime">
        <el-date-picker v-model="queryParams.completionTime" style="width: 240px" value-format="yyyy-MM-dd HH:mm:ss"
                        type="daterange"
                        range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"
                        :default-time="['00:00:00', '23:59:59']"
        />
      </el-form-item>
      <el-form-item label="收货时间" prop="receivingTime">
        <el-date-picker v-model="queryParams.receivingTime" style="width: 240px" value-format="yyyy-MM-dd HH:mm:ss"
                        type="daterange"
                        range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"
                        :default-time="['00:00:00', '23:59:59']"
        />
      </el-form-item>
      <el-form-item label="物流单号" prop="trackingNumber">
        <el-input v-model="queryParams.trackingNumber" placeholder="请输入物流单号" clearable
                  @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>


    <!-- 发货导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
                 :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
                 :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport"/>
            是否更新已经存在的发货数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                   @click="importTemplate">下载模板
          </el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="info" icon="el-icon-upload2" size="mini" @click="handleImport"
                   v-hasPermi="['channelOrder:app-channel-order:import']">发货导入
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                   :loading="exportLoading"
                   v-hasPermi="['channelOrder:app-channel-order:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 列表 -->
    <el-table v-loading="loading" border  :max-height="tableHeight" :data="list">
      <el-table-column label="操作" align="center" width="100" fixed="left" class-name="small-padding fixed-width">
        <template v-slot="scope">
          <el-button v-if="scope.row.channelStatus === 1 && [2,3].includes(scope.row.merchantStatus)" size="mini" type="text" icon="el-icon-edit"
                     @click="handleShipments(scope.row,scope.index)"
                     v-hasPermi="['channelOrder:app-channel-order:shipments']"
          >发货
          </el-button>

          <el-button size="mini" type="text" icon="el-icon-view" @click="handleView(scope.row,scope.index)"
                     v-hasPermi="['channelOrder:app-channel-order:detail']"
          >订单详细
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="自增主键" v-if="false" align="center" prop="id"/>
      <el-table-column label="订单号" align="center" prop="channelOrderNo"/>
      <el-table-column label="商户单订单号" align="center" prop="merchantOrderNo" width="150" fixed="left"/>
      <el-table-column label="渠道用户名称" align="center" prop="channelUserName"/>
      <el-table-column label="渠道用户编码" align="center" prop="channelUserNo"/>
      <el-table-column label="联系方式" align="center" prop="channelUserPhone"/>
      <el-table-column label="订单状态" align="center" prop="channelStatus">
        <template v-slot="scope">
          <dict-tag :type="DICT_TYPE.pc_app_channel_status" :value="scope.row.channelStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="商户订单状态" align="center" prop="merchantStatus">
        <template v-slot="scope">
          <dict-tag :type="DICT_TYPE.app_merchant_status" :value="scope.row.merchantStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="支付状态" align="center" prop="payStatus">
        <template v-slot="scope">
          <dict-tag :type="DICT_TYPE.app_pay_status" :value="scope.row.payStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="手机品牌" align="center" prop="brand"/>
      <el-table-column label="手机型号" align="center" prop="model"/>
      <el-table-column label="型号类型" align="center" prop="modelType"/>
      <el-table-column label="订单金额" align="center" prop="originalPrice"/>
      <el-table-column label="预付款" align="center" prop="advancePrice"/>
      <el-table-column label="尾款" align="center" prop="trailPrice"/>
      <el-table-column label="退款金额" align="center" prop="refundPrice"/>
      <el-table-column label="订单时间" align="center" prop="channelOrderTime" width="180">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.channelOrderTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="完成时间" align="center" prop="completionTime" width="180">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.completionTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="付款时间" align="center" prop="payTime" width="180">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.payTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="收货时间" align="center" prop="receivingTime" width="180">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.receivingTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="物流单号" align="center" prop="trackingNumber"/>
    </el-table>
    <!-- 分页组件 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize"
                @pagination="getList"
    />

    <!-- 订单详情 -->
    <el-dialog title="订单详情" :visible.sync="openDetail" width="800px" append-to-body>
      <el-form ref="form" :model="form" label-width="100px" size="mini">
        <el-row>
          <el-col :span="30">
            <el-form-item label="品牌：">{{ form.brand }}</el-form-item>
          </el-col>
          <el-col :span="30">
            <el-form-item label="手机型号：">{{ form.model }}</el-form-item>
          </el-col>
          <el-col :span="30">
            <el-form-item label="型号类型：">{{ form.modelType }}</el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="IMEI：">{{ form.imei }}</el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="参数：">{{ form.memory }}，{{ form.colour }}，{{ form.buy }}，{{
                form.network
              }}
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="机况：">{{ form.subrackDesc }}</el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="图片：">
              <imageUpload v-model="form.reportImg"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="openDetail = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="title" :visible.sync="open" width="500px" v-dialogDrag append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="订单号" prop="channelOrderNo">
          <el-input v-model="form.channelOrderNo" placeholder="请输入订单号"/>
        </el-form-item>
        <el-form-item label="商户单订单号" prop="merchantOrderNo">
          <el-input v-model="form.merchantOrderNo" placeholder="请输入商户单订单号"/>
        </el-form-item>
        <el-form-item label="渠道用户" prop="channelUserId">
          <el-input v-model="form.channelUserId" placeholder="请输入渠道用户"/>
        </el-form-item>
        <el-form-item label="联系方式" prop="channelUserPhone">
          <el-input v-model="form.channelUserPhone" placeholder="请输入联系方式"/>
        </el-form-item>
        <el-form-item label="支付状态" prop="payStatus">
          <el-radio-group v-model="form.payStatus">
            <el-radio label="1">请选择字典生成</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="订单状态channelOrderTime" prop="channelStatus">
          <el-radio-group v-model="form.channelStatus">
            <el-radio label="1">请选择字典生成</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="回收价" prop="recovery">
          <el-input v-model="form.recovery" placeholder="请输入回收价"/>
        </el-form-item>
        <el-form-item label="尾款" prop="advancePrice">
          <el-input v-model="form.advancePrice" placeholder="请输入尾款"/>
        </el-form-item>
        <el-form-item label="退款金额" prop="refundPrice">
          <el-input v-model="form.refundPrice" placeholder="请输入退款金额"/>
        </el-form-item>
        <el-form-item label="报价单ID" prop="reportId">
          <el-input v-model="form.reportId" placeholder="请输入报价单ID"/>
        </el-form-item>
        <el-form-item label="订单时间" prop="channelOrderTime">
          <el-date-picker clearable v-model="form.channelOrderTime" type="date" value-format="timestamp"
                          placeholder="选择订单时间"
          />
        </el-form-item>
        <el-form-item label="完成时间" prop="completionTime">
          <el-date-picker clearable v-model="form.completionTime" type="date" value-format="timestamp"
                          placeholder="选择完成时间"
          />
        </el-form-item>
        <el-form-item label="付款时间" prop="payTime">
          <el-date-picker clearable v-model="form.payTime" type="date" value-format="timestamp" placeholder="选择付款时间"/>
        </el-form-item>
        <el-form-item label="收货时间" prop="receivingTime">
          <el-date-picker clearable v-model="form.receivingTime" type="date" value-format="timestamp"
                          placeholder="选择收货时间"
          />
        </el-form-item>
        <el-form-item label="物流单号" prop="trackingNumber">
          <el-input v-model="form.trackingNumber" placeholder="请输入物流单号"/>
        </el-form-item>
        <el-form-item label="审核状态" prop="checkStatus">
          <el-radio-group v-model="form.checkStatus">
            <el-radio label="1">请选择字典生成</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核备注" prop="checkRemark">
          <el-input v-model="form.checkRemark" placeholder="请输入审核备注"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  createAppChannelOrder,
  updateAppChannelOrder,
  deleteAppChannelOrder,
  getAppChannelOrder,
  getAppChannelOrderPage,
  exportAppChannelOrderExcel, shipments, importTemplateOrder
} from '@/api/pekingfish/appChannelOrder'
import {getBaseHeader} from '@/utils/request'
import ImageUpload from '@/components/ImageUpload'
import ImagePreview from '@/components/ImagePreview'
import VideoUpload from "@/components/VideoUpload";
import Editor from "@/components/Editor";

export default {
  name: 'AppChannelOrder',
  components: {
    VideoUpload, Editor,
    ImageUpload, ImagePreview,
  },
  data() {
    return {
      tableHeight: document.documentElement.scrollHeight - 245 + "px",
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 渠道单列表
      list: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      openDetail: false,

      // 发货导入参数
      upload: {
        // 是否显示弹出层（发货导入）
        open: false,
        // 弹出层标题（发货导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的发货数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: getBaseHeader(),
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/admin-api/pekingfish/app-channel-order/import'
      },
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        channelOrderNo: null,
        merchantOrderNo: null,
        channelUserId: null,
        channelUserPhone: null,
        payStatus: null,
        channelStatus: null,
        recovery: null,
        advancePrice: null,
        refundPrice: null,
        reportId: null,
        createTime: [],
        channelOrderTime: [],
        completionTime: [],
        payTime: [],
        receivingTime: [],
        trackingNumber: null,
        checkStatus: null,
        checkRemark: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        merchantOrderNo: [{required: true, message: '商户单订单号不能为空', trigger: 'blur'}]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true
      // 执行查询
      getAppChannelOrderPage(this.queryParams).then(response => {
        this.list = response.data.list
        this.total = response.data.total
        this.loading = false
      })
    },
    /** 取消按钮 */
    cancel() {
      this.open = false
      this.reset()
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: undefined,
        channelOrderNo: undefined,
        merchantOrderNo: undefined,
        channelUserId: undefined,
        channelUserPhone: undefined,
        payStatus: undefined,
        channelStatus: undefined,
        recovery: undefined,
        advancePrice: undefined,
        refundPrice: undefined,
        reportId: undefined,
        channelOrderTime: undefined,
        completionTime: undefined,
        payTime: undefined,
        receivingTime: undefined,
        trackingNumber: undefined,
        checkStatus: undefined,
        checkRemark: undefined
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },


    /** 发货按钮操作 */
    handleShipments(row) {
      this.$prompt('请输入"' + row.channelOrderNo + '"的物流单号', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(({value}) => {
        shipments(row.id, value).then(response => {
          this.getList()
          this.$modal.msgSuccess('发货成功')
        })
      }).catch(() => {
      })
    },
    /** 详细按钮操作 */
    handleView(row) {
      this.openDetail = true
      this.form = row
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加渠道单'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id
      getAppChannelOrder(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = '修改渠道单'
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (!valid) {
          return
        }
        // 修改的提交
        if (this.form.id != null) {
          updateAppChannelOrder(this.form).then(response => {
            this.$modal.msgSuccess('修改成功')
            this.open = false
            this.getList()
          })
          return
        }
        // 添加的提交
        createAppChannelOrder(this.form).then(response => {
          this.$modal.msgSuccess('新增成功')
          this.open = false
          this.getList()
        })
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id
      this.$modal.confirm('是否确认删除渠道单编号为"' + id + '"的数据项?').then(function () {
        return deleteAppChannelOrder(id)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      })
    },

    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "物流单号导入";
      this.upload.open = true;
    },

    /** 下载模板操作 */
    importTemplate() {
      importTemplateOrder().then(response => {
        this.$download.excel(response, '批量发货导入模板.xls');
      });
    },

    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      if (response.code !== 0) {
        this.$modal.msgError(response.msg)
        return;
      }
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      // 拼接提示语
      let data = response.data;
      let text = '创建成功数量：' + data.createUsernames.length;
      for (const username of data.createUsernames) {
        text += '<br />&nbsp;&nbsp;&nbsp;&nbsp;' + username;
      }
      text += '<br />更新成功数量：' + data.updateUsernames.length;
      for (const username of data.updateUsernames) {
        text += '<br />&nbsp;&nbsp;&nbsp;&nbsp;' + username;
      }
      text += '<br />更新失败数量：' + Object.keys(data.failureUsernames).length;
      for (const username in data.failureUsernames) {
        text += '<br />&nbsp;&nbsp;&nbsp;&nbsp;' + username + '：' + data.failureUsernames[username];
      }
      this.$alert(text, "导入结果", {dangerouslyUseHTMLString: true});
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    /** 导出按钮操作 */
    handleExport() {
      // 处理查询参数
      let params = {...this.queryParams}
      params.pageNo = undefined
      params.pageSize = undefined
      this.$modal.confirm('是否确认导出所有渠道单数据项?').then(() => {
        this.exportLoading = true
        return exportAppChannelOrderExcel(params)
      }).then(response => {
        this.$download.excel(response, '渠道单.xls')
        this.exportLoading = false
      }).catch(() => {
      })
    }
  }
}
</script>
